package cn.yhjz.common.util;

import java.security.MessageDigest;

public class FileUtil {
    /**
     * 计算文件hash值
     */
    public static String hashFile(byte[] b) {
        String sha256 = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(b, 0, b.length);
            byte[] digest = md.digest();
            sha256 = byte2hexLower(digest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sha256;
    }

    /**
     * 整数转16进制
     *
     * @param b
     * @return
     */
    private static String byte2hexLower(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int i = 0; i < b.length; i++) {
            stmp = Integer.toHexString(b[i] & 0XFF);
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs;
    }
}
